import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router"
import nprogress from "nprogress"
import localCache from "@/utils/cache"

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/login",
    component: () => import("@/views/login/index.vue")
  },
  {
    name: "main",
    path: "/main",
    component: () => import("@/views/main/main.vue"),
    children: []
  },

  {
    path: "/:pathMatch(.*)*",
    name: "404 not found",
    component: () => import("@/views/ErrorPage/404.vue")
  }
  // {
  //   path: "/about",
  //   name: "About",
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ "../views/About.vue")
  // }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(to => {
  if (to.path !== "/login") {
    const token = localCache.getCache("token")
    if (!token) {
      return "/login"
    }
    nprogress.start()
    if (to.path === "/main") {
      return "/main/analysis/overview"
      // return firstRoute?.path
    }
  }
})
router.afterEach(() => {
  nprogress.done()
})

export default router
